import json
import pexpect

def load_config(config_file='config.json'):
    """读取 JSON 配置文件"""
    try:
        with open(config_file, 'r', encoding='utf-8') as f:
            config = json.load(f)
        return config
    except FileNotFoundError:
        print(f"错误：找不到配置文件 {config_file}")
        exit(1)
    except json.JSONDecodeError:
        print(f"错误：配置文件 {config_file} 格式不正确")
        exit(1)

def decompression_ogpkg(config):
    """解压og安装包"""
    ogpkg_name = config['ogpkg_name']
    ogpkgom_name = config['ogpkg_name'].replace("All", "OM")

    print("解压all命令为：" + "tar -zxvf " + config['ogpkg_path'] + "/" +  config['ogpkg_name'] + " -C " + config['ogpkg_path'])
    print("解压om工具命令为：" + "tar -zxvf " + config['ogpkg_path'] + "/" + ogpkgom_name + " -C " + config['ogpkg_path'])

    # 解压 All 包
    tarzxvfall = pexpect.spawn("tar -zxvf " + config['ogpkg_path'] + "/" + config['ogpkg_name'] + " -C " + config['ogpkg_path'], timeout=300)
    tarzxvfall.wait()
    print("安装包已经解压完成")

    # 解压 OM 包
    tarzxvfom = pexpect.spawn("tar -zxvf " + config['ogpkg_path'] + "/" + ogpkgom_name + " -C " + config['ogpkg_path'], timeout=300)
    tarzxvfom.expect(pexpect.EOF)
    tarzxvfom.wait()
    print("运维工具已经解压完成")

def print_config_info(config):
    """打印配置信息"""
    print("opengauss安装包位置：" + config['ogpkg_path'])
    print("omm用户的密码为：" + config['ommuserpw'])
    print("自动化安装脚本路径为：" + config['install_script_path'])
    print("配置文件名为：" + config['cluster_standalone_name'])

def run_preinstall_script(config):
    """执行预安装脚本 gs_preinstall"""
    pkg_path = config['ogpkg_path']
    ommuserpw = config['ommuserpw']
    cluster_standalone_name = config['cluster_standalone_name']
    preinstall_path = f"{pkg_path}/script/gs_preinstall"
    print("预安装脚本路径:", preinstall_path)
    print("预安装命令为:" + preinstall_path + " -U omm -G dbgrp -X " + config['install_script_path'] + "/" + cluster_standalone_name )
    preinstall_exec = pexpect.spawn(preinstall_path + " -U omm -G dbgrp -X " + config['install_script_path'] + "/" + cluster_standalone_name , timeout=300)

    # 创建omm用户
    preinstall_exec.expect("you want to create the user")
    preinstall_exec.sendline("yes")
    
    # 为omm用户设置密码
    preinstall_exec.expect("password for cluster user")
    preinstall_exec.sendline(ommuserpw)

    # 再次确认密码
    preinstall_exec.expect("password for cluster user again")
    preinstall_exec.sendline(ommuserpw)

    # 输出整个过程的输出结果（可选）
    print(preinstall_exec.before.decode())  # 显示之前的内容
    print(preinstall_exec.after.decode())   # 显示匹配的内容

    # 等待脚本执行结束
    preinstall_exec.wait()
    print("预安装脚本已执行完毕")

def switch_omm():
    # 用omm用户执行安装脚本
    switch_omm_cmd = "su - omm"
    print("切换为omm用户")
    
    # 验证用户是否已经成功切换
    switch_omm = pexpect.spawn("su - omm")
    switch_omm.sendline('whoami')
    switch_omm.expect('omm')
    print("已成功切换为 omm 用户")

def run_install(config):
    print("执行opengauss原生安装脚本：" + "gs_install -X " + config['install_script_path'] + "/" +config['cluster_standalone_name'] )
    print("数据库omm用户的密码为：" + config['dbommpw'])
    preinstall_exec = pexpect.spawn("gs_install -X " + config['install_script_path'] + "/" + config['cluster_standalone_name'] , timeout=300)
    preinstall_exec.expect("enter password for database")
    preinstall_exec.sendline(config['dbommpw'])

    preinstall_exec.expect("Please repeat for database")
    preinstall_exec.sendline(config['dbommpw'])
    # 等待脚本执行结束
    preinstall_exec.wait()
    print("安装脚本已执行完毕")

def run_install_as_omm(config):
    print("以 omm 用户身份启动 gs_install 安装")

    # 在一个 spawn 实例中完成切换用户并执行命令
    child = pexpect.spawn("su - omm")
    child.sendline('whoami')
    child.expect('omm')
    print("已成功切换为 omm 用户")

    # 执行安装命令
    install_cmd = f"gs_install -X {config['install_script_path']}/{config['cluster_standalone_name']}"
    child.sendline(install_cmd)

    # 输入数据库密码
    child.expect("enter password for database", timeout=600)
    child.sendline(config['dbommpw'])

    child.expect("Please repeat for database", timeout=600)
    child.sendline(config['dbommpw'])

    # 等待执行完成
    print("已经发送完所有指令，等待安装完毕...")
    child.expect("end deploy..", timeout=600)  # 根据实际情况修改关键词
    print("安装已完成")
    child.close()
    print("安装脚本已执行完毕")

def xml_permission_to_omm(config):
    print("修改文件的所属用户：" + "chown omm:dbgrp " + config['install_script_path'] + "/" + config['cluster_standalone_name'])
    print("修改读写执行权限：" + "chmod 755 " + config['install_script_path'] + "/" + config['cluster_standalone_name'])
    xmlchownpermissiontoomm = pexpect.spawn("chown omm:dbgrp " + config['install_script_path'] + "/" + config['cluster_standalone_name'])
    xmlchmodpermissiontoomm = pexpect.spawn("chmod 755 " + config['install_script_path'] + "/" + config['cluster_standalone_name'])

def main():
    """主程序入口"""
    config = load_config()
    decompression_ogpkg(config)
    print_config_info(config)
    run_preinstall_script(config)
    xml_permission_to_omm(config)
    run_install_as_omm(config)

if __name__ == "__main__":
    main()

